package com.qymerge.manage.picture.controller;

import com.qymerge.manage.core.constant.ParamKey;
import com.qymerge.manage.core.controller.BaseController;
import com.qymerge.manage.core.enums.ParentTypes;
import com.qymerge.manage.core.utils.FileUtil;
import com.qymerge.manage.core.utils.PrintCodeUtils;
import com.qymerge.manage.picture.service.PictureService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.support.DefaultMultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * Desc
 * User cong.li
 * Date 2017/5/6
 * Time 18:55
 */
@Controller
@RequestMapping(value = "/picture")
public class PictureController extends BaseController {

    @Autowired
    private PictureService pictureService;

    /**
     * 上传图片
     *
     * @param typeId
     * @param request
     * @param response
     * @param callback
     */
    @RequestMapping(value = "/uploadByUE/{typeId}", method = RequestMethod.POST)
    @ResponseBody
    public Object uploadByUE(
            @PathVariable(value = "typeId") int typeId,
            HttpServletRequest request, HttpServletResponse response,
            @RequestParam(defaultValue = ParamKey.In.empty) String callback) {

        Map resultMap = new HashMap();
        resultMap.put("state", "FAIL");

        if (!(request instanceof MultipartHttpServletRequest)) {
            PrintCodeUtils.printError(response, "提交方式必须是 multipart/form-data", callback);
            return resultMap;
        }
        MultipartFile uploadify = ((DefaultMultipartHttpServletRequest) request).getFile("img");
        if (uploadify == null || uploadify.isEmpty()) {
            PrintCodeUtils.printError(response, "请选择文件", callback);
            return resultMap;
        }

        if (ParentTypes.get(typeId) == null) {
            PrintCodeUtils.printError(response, "类型尚未开放", callback);
            return resultMap;
        }

        File file = null;
        try {
            file = FileUtil.multipartToFile(uploadify);
        } catch (IOException e) {
            e.printStackTrace();
        }

        return pictureService.uploadImg(file, typeId);
    }

}
